<?php
namespace M\Action;
class YibanAction extends BaseAction {
    //前置操作方法
    public function _before_index(){
        
    }

    //易班登录
    function index(){
    	//获取配置
    	$oauth2=C('oauth2');
    	$appid=$oauth2['yiban']['AppID'];
    	$appsecret=$oauth2['yiban']['AppSecret'];
    	$callback=$oauth2['yiban']['CallBack'];
    	//引入易班类
    	import('Common.ORG.Yiban.classes.yb-globals');    	
    	$api = \YBOpenApi::getInstance()->init($appid, $appsecret, $callback);
    	$iapp  = $api->getIApp();
    	//轻应用获取access_token，未授权则跳转至授权页面
    	$info = $iapp->perform();
    	$token = $info['visit_oauth']['access_token'];//轻应用获取的token
    	//初始化配置信息，并获取token
    	$api->bind($token);
    	$yiban_user=$api->request('user/me');
    	if($yiban_user['info']){
    		//获取用户信息放在session里
    		session_start();
    		$_SESSION['yiban_info']=$yiban_user['info'];
    		$_SESSION['yiban_info']['access_token']=$token;
    		if($_SESSION['yiban_info']){
    			//$api->request('oauth/revoke_token', array('client_id'=>$api->getConfig('appid')), true);
    			header("Location: /M/Yiban/oauth_redirect");
    			exit;
    		}else{
    			//重新授权
    			header('location: '.$iapp->forwardurl());
    			exit;
    		}
    	}else{
    		echo '<pre>';
    		echo '获取易班信息失败';
    		header('location: '.$iapp->forwardurl());
    		exit;
    	}
    }  
    //处理登录以后的信息
    function oauth_redirect(){
    	//易班APP里
    	if(isset($_SESSION['yiban_info']) && !empty($_SESSION['yiban_info']['yb_userid'])){
    		$yiban_openid=$_SESSION['yiban_info']['yb_userid'];
    	}else{
    		$yiban_openid='';
    	}
    	// 1.检测当前yiban_openid是否已经绑定，如果存在跳转到登录页面
    	if($yiban_openid){
    		//判断用户存在，存在直接跳转登录
    		$sns_info = M("user")->where("yiban_openid = '".$yiban_openid."'")->find();
    		if (!$sns_info){//第一次登陆 注册易班账号
    			$yiban_info=$_SESSION['yiban_info'];
    			//第一次登录注册会员并且绑定   json_encode($yiban_info);
    			//插入用户表
    			$data = array();
    			$data['username'] = $yiban_info['yb_username'];
    			$data['nickname'] = isset($data['nickname'])?$data['nickname']:$yiban_info['yb_username'];
    			$data['phone'] = '';
    			$data['email'] = '';
    			$data['password'] = md5(date("YmdHis").rand(100,999));
    			$data['money'] = 0;
    			$data['avatar'] =$yiban_info['yb_userhead'];
    			$data['frozen'] = 0;
    			$data['score'] = 0;
    			$data['reg_ip'] = get_client_ip();
    			$data['reg_time'] = time();
    			$data['last_time'] = 0;
    			$data['last_ip'] = 0;
    			$data['login_count'] = 0;
    			$data['create_time'] = time();
    			$data['status'] = 1;
    			$data['state'] = 1;
    			$data['yiban_openid'] = $yiban_openid;
    			$data['yiban_info'] = json_encode($yiban_info);
    			$data['fuid'] = isset($data['fuid'])?$data['fuid']:0;
    			$data['guid'] = isset($data['guid'])?$data['guid']:0;
    			if(M("user")->create($data)){
    				$uid = M("user") -> add();
    				if($uid){
    				    //注册送积分
    				    $res=$uid;
    				    $score=trim(C('yh_reinte'));
    				    $reinvi=F('reinvi_'.$res);
    				    if($score>0 && $res && false ===$reinvi){
    				        M("user")->where("id='".$res."'")->setInc('score',$score);
    				        M('basklistlogo')->add(array(
    				        'uid'=>$res,
    				        'integray'=>$score,
    				        'remark'=>'注册送+'.$score,
    				        'order_sn'=>'--',
    				        'create_time'=>NOW_TIME,
    				        ));
    				        F('reinvi_'.$res,$res);
    				    }
    					//获取用户信息保存到session
    					$where['id'] = $uid;
    					$user_info = M('user')->where($where)->field('tb_open_uid,id,username,openid,nickname,phone,email,fuid,guid,invocode,avatar,password,score,tbname,money,webmaster,webmaster_rate,oid,webmaster_pid')->find();
    					if($user_info){
	    					session('user_info', $user_info);
	    					cookie("islogin", '1');
	    					if($this->isMobile()){
	    						$url='/M/index.html';
	    					}else{
	    						$url='/user/ucenter.html';	
	    					}
	    					header("Location: ".$url);
	    					exit;
    					}
    				}else{
    					$this -> error("登录失败");
    				}
    			}
    		} else {//已经存在直接登录
    			$yiban_info=$_SESSION['yiban_info'];
    			//更新登录时间
    			$data['last_time'] = time();
    			$data['last_ip'] = get_client_ip();
    			$data['login_count'] = array('exp','login_count+1');
    			$data['nickname'] = $yiban_info['yb_username'];
    			$data['avatar'] = $yiban_info['yb_userhead'];
    			$data['yiban_info'] = json_encode($yiban_info);
    			M("user")->where(array("id"=>$sns_info['id']))->save($data);
    			
    			//获取用户信息
    			$where['id'] = $sns_info['id'];
    			$user_info = M('user')->where($where)->field('tb_open_uid,id,username,openid,nickname,phone,email,fuid,guid,invocode,avatar,password,score,tbname,money,webmaster,webmaster_rate,oid,webmaster_pid')->find();
    			session('user_info', $user_info);
	    		cookie("islogin", '1');
    			if($this->isMobile()){
	    			$url='/M/index.html';
	    		}else{
	    			$url='/user/ucenter.html';	
	    		}
	    		header("Location: ".$url);
	    		exit;
    			exit;
    		}
    	}else{
    		$redirect ='/M/yiban/index';
    		$this->redirect($redirect);
    	}
    }
}
